#pragma once
#include"Common.h"

template <class T>
class Objectpool
{
public:
    T *New()
    {
        T *obj = nullptr;
        // 优先使用freelist里面的内存
        if (_freeList)
        {
            void *next = *((void **)_freeList);
            obj = _freeList;

            _freeList = next;
        }
        else
        {
            if (_residue < sizeof(T)) // 如果没有，申请
            {
                _residue = 128 * 2024;
                _memory = (char *)malloc(_residue);
                if (_memory == nullptr) // 如果没有剩余了，重新开
                {
                    throw bad_alloc();
                }
            }

            T *obj = (T*)_memory;
            szie_t Size = sizeof(T) < sizeof(void*) ? sizeof(void*) : sizeof(T);
            _memory += Size;
            _residue -= Size;
        }
        new(obj)T;

        return obj;
    }

    void Delete(T *obj)
    {
        obj->~T();

        *(void **)obj = _freeList;
        _freeList = obj;
    }

private:
    char *_memory = nullptr;
    size_t _residue = 0;
    void *_freeList = nullptr;
};